import 'dart:io';

import 'package:e_reception_flutter/constants/account_constant.dart';
import 'package:flutter/widgets.dart';
import 'package:sharesdk_plugin/sharesdk_plugin.dart';
import 'package:vg_base/vg_log_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_base/vg_widget_lib.dart';
import 'package:vg_flutter_base_moudle/vg_moudle_constants_lib.dart';

import 'share_utils.dart';
import 'vo/share_param_bean.dart';

///分享
class ShareRepository {
  static ShareRepository _instance;

  static ShareRepository getInstance() {
    if (_instance == null) {
      _instance = new ShareRepository().._initRegister();
    }
    return _instance;
  }

 /// 0 ===> 不同意隐私政策
 /// 1 ===> 同意
 submitPrivacyGrantResult(BuildContext context, Function confirmFunction) {
   SharesdkPlugin.uploadPrivacyPermissionStatus("ShareRepository", 1, (bool success) {
     print("ShareRepository 通过隐私协议");
     if (success == true) {
       print("发送链接");
       if (confirmFunction != null) {
         print("调用软件");
         confirmFunction();
       }
     } else {
       print("隐私协议授权提交结果失败");
     }
   });
 }

  ///初始化注册
  void _initRegister() {
    shareSdkVersion();
    ShareSDKRegister register = ShareSDKRegister();
    register.setupWechat(AccountConstant.WX_APPID,
        AccountConstant.WX_SECRET, AccountConstant.WX_UNIVERSAL_LINK);
   // register.setupSinaWeibo("748676835", "0ea00389a26490a00e8e44582d44d696",
   //     "http://www.sharesdk.cn");
   //  register.setupQQ(AccountConstant.QQ_APPID, AccountConstant.QQ_KEY);
    SharesdkPlugin.regist(register);
  }

  void shareSdkVersion() {
    SharesdkPlugin.sdkVersion.then((dynamic version) {
      if (version.length > 0) {
        if (Platform.isIOS) {
          LogUtils.d("ShareSDK iOS 版本:${version.toString()}");
        } else if (Platform.isAndroid) {
          LogUtils.d("ShareSDK Android 版本:${version.toString()}");
        }
      } else {
        LogUtils.d("ShareSDK版本失败");
      }
    });
  }

  /// 分享微博
  void shareSina(BuildContext context, ShareParamsBean uploadBean) {
    if (uploadBean == null) {
      return;
    }

    SharesdkPlugin.share(
        ShareSDKPlatforms.sina,
        _setSSDKMAP(uploadBean),
        (SSDKResponseState state, Map userdata, Map contentEntity,
            SSDKError error) {});
  }

  void shareQZone(BuildContext context, ShareParamsBean uploadBean) {
    SSDKMap params = SSDKMap()
      ..setQQ(
          uploadBean.text,
          uploadBean.title,
          uploadBean.url,
          null,
          null,
          uploadBean.musicUrlAndroid,
          uploadBean.videoUrlAndroid,
          uploadBean.imageUrlAndroid,
          uploadBean.images,
          uploadBean.imageUrlAndroid,
          null,
          uploadBean.url,
          null,
          null,
          uploadBean.contentType ?? SSDKContentTypes.webpage,
          ShareSDKPlatforms.qZone);
    SharesdkPlugin.share(ShareSDKPlatforms.qZone, params,
        (SSDKResponseState state, Map userdata, Map contentEntity,
            SSDKError error) {
      HudUtils.showLoading(context, false);
    });
  }

  ///QQ自定义
  void shareQQCustom(BuildContext context, ShareParamsBean uploadBean) {
    SSDKMap params = SSDKMap()
      ..setQQ(
          uploadBean.text,
          uploadBean.title,
          uploadBean.url,
          null,
          null,
          uploadBean.musicUrlAndroid,
          uploadBean.videoUrlAndroid,
          uploadBean.imageUrlAndroid,
          uploadBean.images,
          uploadBean.imageUrlAndroid,
          null,
          uploadBean.url,
          null,
          null,
          uploadBean.contentType ?? SSDKContentTypes.webpage,
          ShareSDKPlatforms.qq);
    SharesdkPlugin.share(ShareSDKPlatforms.qq, params, (SSDKResponseState state,
        Map userdata, Map contentEntity, SSDKError error) {
//              showAlert(state, error.rawData, context);
      HudUtils.showLoading(context, false);
    });
  }

  /// 分享到朋友圈
  void shareToWeChatTimeLine(BuildContext context, ShareParamsBean uploadBean) {
    if (uploadBean == null) {
      return;
    }
    SharesdkPlugin.share(
        ShareSDKPlatforms.wechatTimeline, _setSSDKMAP(uploadBean),
        (SSDKResponseState state, Map userdata, Map contentEntity,
            SSDKError error) {
      HudUtils.showLoading(context, false);
    });
  }

  ///分享微信
  void shareToWechat(BuildContext context, ShareParamsBean uploadBean,
      {bool showLoading = true}) {
    if (uploadBean == null) {
      return;
    }
    HudUtils.showLoading(context, showLoading);
//    submitPrivacyGrantResult(context, () {
    SharesdkPlugin.share(
        ShareSDKPlatforms.wechatSession, _setSSDKMAP(uploadBean),
        (SSDKResponseState state, Map userdata, Map contentEntity,
            SSDKError error) {
      HudUtils.showLoading(context, false);
//      showAlert(state, error.rawData, context);
    });
//    });
  }

  ///分享图片微信
  void shareImageToWechat(BuildContext context, SSDKMap params,
      {bool showLoading = false, ShareSDKPlatform platforms}) {
    HudUtils.showLoading(context, showLoading);
    SharesdkPlugin.share(
        platforms??ShareSDKPlatforms.wechatSession, params,
            (SSDKResponseState state, Map userdata, Map contentEntity,
            SSDKError error) {
          HudUtils.showLoading(context, false);
        });
  }

  SSDKMap _setSSDKMAP(ShareParamsBean uploadBean) {
    final int limitCount = 100;

    ///过长判断
    if(uploadBean != null){
      if(StringUtils.isNotEmpty(uploadBean?.title) && uploadBean.title.length >= limitCount){
        uploadBean.title = uploadBean.title.substring(0,limitCount);
      }
      if(StringUtils.isNotEmpty(uploadBean?.text) && uploadBean.text.length >= limitCount){
        uploadBean.text = uploadBean.text.substring(0,limitCount);
      }
    }
    String logo = uploadBean?.imageUrlAndroid ?? "" + ImageThumbConstant.LOWEST;
    SSDKMap params = SSDKMap()
      ..setGeneral(
          uploadBean?.title ?? "",
          uploadBean?.text ?? "",
          [uploadBean.images ?? ""],
          logo,
          uploadBean?.imagePathAndroid,
          uploadBean?.url ?? "",
          uploadBean?.titleUrlAndroid ?? "",
          uploadBean?.musicUrlAndroid ?? "",
          uploadBean?.videoUrlAndroid ?? "",
          uploadBean?.filePath ?? "",
          uploadBean?.contentType ?? SSDKContentTypes.webpage);
    return params;
  }

  ///一键分享
  ///根据类型
  void oneKeyShare(BuildContext context, ShareSDKPlatform sdkPlatform,
      ShareParamsBean uploadBean) async {
    if (sdkPlatform == null ||
        sdkPlatform.name == null ||
        sdkPlatform.name == "" ||
        uploadBean == null) {
      ToastUtils.toast(context: context, msg: "分享数据为空");
      return;
    }
    switch (sdkPlatform.name) {
      case "qq":
        if (await ShareUtils.isInstallQQ()) {
          shareQQCustom(context, uploadBean);
        } else {
          ToastUtils.toast(context: context, msg: "请安装qq");
        }
        break;
      case "qZone":
        if (await ShareUtils.isInstallQzone()) {
          shareQZone(context, uploadBean);
        } else {
          ToastUtils.toast(context: context, msg: "请安装qq");
        }
        break;
      case "wechatTimeline":
      case "wechatSession":
        if (await ShareUtils.isInstalledWx()) {

          SharesdkPlugin.share(sdkPlatform, _setSSDKMAP(uploadBean),
              (SSDKResponseState state, Map userdata, Map contentEntity,
                  SSDKError error) {
//              showAlert(state, error.rawData, context);
            HudUtils.showLoading(context, false);
          });
        } else {
          ToastUtils.toast(context: context, msg: "请安装微信");
        }
        break;
      default:
        SharesdkPlugin.share(sdkPlatform, _setSSDKMAP(uploadBean),
            (SSDKResponseState state, Map userdata, Map contentEntity,
                SSDKError error) {
//              showAlert(state, error.rawData, context);
          HudUtils.showLoading(context, false);
        });
    }
  }

  ///回显状态
  void showAlert(SSDKResponseState state, Map content, BuildContext context) {
    String title = "失败";
    switch (state) {
      case SSDKResponseState.Success:
        title = "成功";
        break;
      case SSDKResponseState.Fail:
        title = "失败";
        break;
      case SSDKResponseState.Cancel:
        title = "取消";
        break;
      default:
        title = state.toString();
        break;
    }

    ToastUtils.toast(msg: title ?? "", context: context);
  }
}
